<template>
  <div class="container mx-auto px-4 py-8">
    <h1 class="text-3xl font-bold mb-8">Java 在线学习平台</h1>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
      <div class="md:col-span-2">
        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-2">编写你的 Java 代码：</label>
          <div class="border rounded-lg overflow-hidden">
            <Codemirror
              v-model="code"
              :extensions="extensions"
              :style="{ height: '400px' }"
              :autofocus="true"
              :indent-with-tab="true"
              :tab-size="4"
              :basic-setup="true"
            />
          </div>
        </div>
        <button
          @click="runCode"
          class="bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg transition-colors"
          :disabled="isRunning"
        >
          {{ isRunning ? '执行中...' : '运行代码' }}
        </button>
      </div>
      <div>
        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-2">执行结果：</label>
          <div
            class="border rounded-lg p-4 bg-gray-50 h-[400px] overflow-y-auto whitespace-pre-wrap font-mono text-sm"
          >
            {{ output }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Codemirror } from 'vue-codemirror'
import { java } from '@codemirror/lang-java'
import { oneDark } from '@codemirror/theme-one-dark'
import { autocompletion } from '@codemirror/autocomplete'
import { keymap } from '@codemirror/view'
import { defaultKeymap, indentWithTab } from '@codemirror/commands'

// Java 关键字和常用方法的自动完成
const javaCompletions = {
  keywords: [
    'abstract', 'assert', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'const',
    'continue', 'default', 'do', 'double', 'else', 'enum', 'extends', 'final', 'finally', 'float',
    'for', 'if', 'implements', 'import', 'instanceof', 'int', 'interface', 'long', 'native', 'new',
    'package', 'private', 'protected', 'public', 'return', 'short', 'static', 'strictfp', 'super',
    'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'try', 'void', 'volatile', 'while'
  ],
  methods: [
    'System.out.println', 'System.out.print', 'System.out.printf',
    'String.format', 'String.valueOf', 'String.length', 'String.charAt',
    'String.substring', 'String.indexOf', 'String.lastIndexOf',
    'String.replace', 'String.replaceAll', 'String.split',
    'String.trim', 'String.toLowerCase', 'String.toUpperCase',
    'String.equals', 'String.equalsIgnoreCase', 'String.compareTo',
    'String.compareToIgnoreCase', 'String.startsWith', 'String.endsWith',
    'String.contains', 'String.isEmpty', 'String.concat'
  ]
}

// 自定义自动完成提供者
const customCompletions = autocompletion({
  override: [
    (context) => {
      const word = context.matchBefore(/\w*/)
      if (!word) return null

      const completions = [
        ...javaCompletions.keywords.map(keyword => ({
          label: keyword,
          type: 'keyword'
        })),
        ...javaCompletions.methods.map(method => ({
          label: method,
          type: 'function'
        }))
      ]

      return {
        from: word.from,
        options: completions
      }
    }
  ]
})

const config = useRuntimeConfig()
const code = ref(`public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}`)
const output = ref('')
const isRunning = ref(false)

const extensions = [
  java(),
  oneDark,
  customCompletions,
  keymap.of([
    ...defaultKeymap,
    indentWithTab
  ])
]

async function runCode() {
  if (isRunning.value) return
  
  isRunning.value = true
  output.value = '正在执行...'
  
  try {
    const response = await fetch(`${config.public.apiBase}/api/code/execute`, {
      method: 'POST',
      body: code.value,
      headers: {
        'Content-Type': 'text/plain'
      }
    })
    
    const result = await response.text()
    output.value = result
  } catch (error) {
    output.value = `执行出错：${error.message}`
  } finally {
    isRunning.value = false
  }
}
</script> 